package com.dx.mes.web.login;

import com.alibaba.fastjson.JSONObject;
import com.dx.common.table.ppt.Bis_user;
import com.dx.mes.facade.uas.service.IBisUasFunGrpService;
import com.dx.mes.web.common.authorization.manager.TokenManager;
import com.dx.mes.web.common.authorization.model.TokenModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
public class LoginServlet {

    @Resource
    private IBisUasFunGrpService bisUasFunGrpService;

    @Autowired
    private TokenManager manager;

    @RequestMapping("/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String userID = null;
        String password = null;
        // 获取用户输入的用户名
        String userID1 = request.getParameter("userName");
        if(userID1 != null){
              userID = new String(userID1.getBytes(),"UTF-8");
            //userID = URLEncoder.encode(userID1, "utf-8");
        }
        // 获取用户输入的密码
        String password1 = request.getParameter("password");
        if(password1 != null){
            password = new String(password1.getBytes(),"UTF-8");
            //URLEncoder.encode(password1, "utf-8");
        }
        if ( (userID != null && !userID.equals("")) && (password != null && !password.equals("")) ) {
            boolean flag = bisUasFunGrpService.getUserByUsrIdAndPwd(userID, password);
            // 若用户名和密码一致，则登录成功（此处实际上，应该查询数据库）
            if (flag) {
                Bis_user user = bisUasFunGrpService.getUserByUsrID(userID);
                // 把用户名存储在session中
               // String usr_name1 = user.getUsr_name();
                String usr_name1 =  user.getUsr_id();

                String usr_name = URLEncoder.encode(usr_name1, "utf-8");
                request.getSession().setAttribute("user", userID);
                request.getSession().setAttribute("userid", userID);
                // 向客户端写入cookie，名为为ssoName
                Cookie c = new Cookie("ssoName", usr_name);
                c.setPath("/");
                response.addCookie(c);// 把cookie添加到response中
                // 向客户端写入cookie，名为为ssoName
                Cookie c1 = new Cookie("sso", userID);
                c1.setPath("/");
                response.addCookie(c1);// 把cookie添加到response中
                return "redirect:/home.jsp";
            }
        }
        request.setAttribute("loginErr","用户名或密码错误！");
       return "index.jsp";
    }

    @RequestMapping("/appLogin.do")
    @ResponseBody
    public JSONObject appLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String userID = null;
        String password = null;
        // 获取用户输入的用户名
        String userID1 = request.getParameter("loginName");
        if (userID1 != null) {
            userID = new String(userID1.getBytes(), "UTF-8");
        }
        // 获取用户输入的密码
        String password1 = request.getParameter("password");
        if (password1 != null) {
            password = new String(password1.getBytes(), "UTF-8");
        }
        if ((userID != null && !userID.equals("")) && (password != null && !password.equals(""))) {
            boolean flag = bisUasFunGrpService.getUserByUsrIdAndPwd(userID, password);
            // 若用户名和密码一致，则登录成功（此处实际上，应该查询数据库）
            if (flag) {
                Bis_user user = bisUasFunGrpService.getUserByUsrID(userID);
                // 把用户名存储在session中
                String usr_name1 = user.getUsr_id();
                TokenModel model = manager.createToken(usr_name1);
                JSONObject msgJson = new JSONObject();
                msgJson.put("rtn_code","0000000");
                msgJson.put("rtn_mesg","SUCCESS");
                msgJson.put("userId",model.getUserId());
                msgJson.put("token",model.getToken());
//                String outMsg = JacksonUtil.toJSONStr(msgJson);
//                response.getWriter().write(outMsg);
                return msgJson;
//                response.setStatus(HttpServletResponse.SC_OK);
            }
        }
//        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        JSONObject msgJson = new JSONObject();
        msgJson.put("rtn_code","9999999");
        msgJson.put("rtn_mesg","ERROR");
//        String outMsg = JacksonUtil.toJSONStr(msgJson);
        return  msgJson;
    }

}
